package cn.spream.jstudy.redis.dao.impl;

import org.springframework.dao.DataAccessException;
import org.springframework.data.redis.connection.RedisConnection;
import org.springframework.data.redis.core.RedisCallback;
import org.springframework.data.redis.core.StringRedisTemplate;
import cn.spream.jstudy.redis.dao.UserDao;
import cn.spream.jstudy.redis.domain.User;

/**
 * Created with IntelliJ IDEA.
 * User: sjx
 * Date: 14-1-10
 * Time: 下午5:37
 * To change this template use File | Settings | File Templates.
 */
public class UserDaoImpl implements UserDao {

    private StringRedisTemplate redisTemplate;
    private final String REDIS_USER_KEY = "user.id.";

    @Override
    public boolean add(final User user) {
        return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte key[] = redisTemplate.getStringSerializer().serialize(REDIS_USER_KEY + user.getId());
                byte value[] = redisTemplate.getStringSerializer().serialize(user.getName());
                redisConnection.set(key, value);
                return true;
            }
        });
    }

    @Override
    public boolean delete(final long id) {
        return (Boolean) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte key[] = redisTemplate.getStringSerializer().serialize(REDIS_USER_KEY + id);
                redisConnection.del(key);
                return true;
            }
        });
    }

    @Override
    public boolean update(final User user) {
        return add(user);
    }

    @Override
    public User getById(final long id) {
        return (User) redisTemplate.execute(new RedisCallback<Object>() {
            @Override
            public Object doInRedis(RedisConnection redisConnection) throws DataAccessException {
                byte key[] = redisTemplate.getStringSerializer().serialize(REDIS_USER_KEY + id);
                byte value[] = redisConnection.get(key);
                if (value != null && value.length > 0) {
                    String name = redisTemplate.getStringSerializer().deserialize(value);
                    User user = new User();
                    user.setId(id);
                    user.setName(name);
                    return user;
                }
                return null;
            }
        });
    }

    public StringRedisTemplate getRedisTemplate() {
        return redisTemplate;
    }

    public void setRedisTemplate(StringRedisTemplate redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
}
